package com.mooc.mymooc.controller;

import com.mooc.mymooc.pojo.*;
import com.mooc.mymooc.service.MoocService;
import com.mooc.mymooc.utils.common.DateFormater;
import com.mooc.mymooc.utils.common.MakeCode;
import com.mooc.mymooc.utils.common.SendEmail;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;

@Controller
public class MainController {
    @Autowired
    private MoocService moocService;
    @RequestMapping(value = "/")
    public String showIndexs(){
        return "redirect:/index";
    }
    @RequestMapping(value = "/index")
    public String index(Model model) {
        List<Course> courseList = this.moocService.findAllCourseInBackGround(new Course());
        List<Organization> organizationList = this.moocService.findAllOrgUseInBackGround(new Organization());
        List<Banner> banners = this.moocService.findAllBanner();
        model.addAttribute("banners",banners);
        model.addAttribute("courses",courseList);
        model.addAttribute("orgs",organizationList);
        return "index";
    }

    @RequestMapping(value = "/login")
    public String login(HttpSession session, HttpServletRequest request,
                        String from, HttpServletResponse response) throws Exception {
        String fromUrl = request.getHeader("referer");
        if (from == null || from.equals("")) {
            String fromURI = fromUrl.substring(21);
            session.setAttribute("fromUrl", fromURI);
        } else {
            session.setAttribute("fromUrl", from);
        }
        return "login";
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param httpSession
     * @param request
     * @return
     */
    @RequestMapping(value = "/dologin")
    public String doLogin(String username, String password,
                          HttpSession httpSession, HttpServletRequest request) {
        User user = this.moocService.login(username, password);
        if (user != null) {
            Integer active = this.moocService.checkActive(user.getId());
            if (user != null && active == 1) {
                httpSession.setAttribute("user_session", user);
                String toUri = (String) httpSession.getAttribute("fromUrl");
                if (toUri.equals("/index.jsp")) {
                    toUri = "/index";
                }
                return "redirect:" + toUri;
            } else {
                if (user == null) {
                    request.setAttribute("message", "用户名或密码错误");
                    return "login";
                }
                if (active == 0) {
                    request.setAttribute("message", "用户未激活");
                    return "login";
                }
                request.setAttribute("message", "未知错误");
                return "login";
            }
        }
        request.setAttribute("message", "用户名或密码错误");
        return "login";
    }

    /**
     * 注销
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session, Model model) {
        session.invalidate();
        return "redirect:/index";
    }

    /**
     * 跳转个人中心
     */
    @RequestMapping(value = "/usercenter")
    public String userCenter(HttpServletRequest request, Model model) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("user_session");
        User newUser = this.moocService.findById(user.getId());
        Date date = newUser.getBirthday();
        String birthday = DateFormater.doFormat(date, "yyyy-MM-dd");
        model.addAttribute("user", newUser);
        model.addAttribute("birthday", birthday);
        return "usercenter-info";
    }

    /**
     * 个人中心修改用户信息
     *
     * @param user
     * @param session
     * @return
     */
    @RequestMapping(value = "/users/info")
    @ResponseBody
    public User userSave(@RequestBody User user, HttpSession session) {
        User user2 = (User) session.getAttribute("user_session");
        user.setId(user2.getId());
        Integer rows = this.moocService.updateUser(user);
        User user1 = this.moocService.findById(user.getId());
        if (rows > 0) {
            return user1;
        } else {
            return null;
        }
    }

    /**
     * 修改用户头像
     *
     * @param image
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/users/image/upload")
    public String uploadImage(MultipartFile image, Model model, HttpServletRequest request) {
        if (!image.isEmpty() && image.getSize() > 0) {
            String realName = image.getOriginalFilename();
            String path = request.getSession().getServletContext().getRealPath("") + "/upload/";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            User user = (User) request.getSession().getAttribute("user_session");
            String newFileName = UUID.randomUUID() + realName;
            try {
                image.transferTo(new File(path + File.separator + newFileName));
            } catch (Exception e) {
                e.printStackTrace();
            }
            User user1 = new User();
            user1.setId(user.getId());
            user1.setImage("/upload/" + newFileName);
            this.moocService.updateImage(user1);
            User user2 = this.moocService.findById(user.getId());
            request.getSession().setAttribute("user_session", user2);
            model.addAttribute("user", user2);

        }
        return "redirect:/usercenter";
    }

    /**
     * 发送验证码
     *
     * @param email
     * @param request
     * @return
     */
    @RequestMapping(value = "/users/sendCode")
    @ResponseBody
    public Object sendCode(@RequestBody Email email, HttpServletRequest request) {
        String code = MakeCode.code(16);
        String content = "欢迎使用慕课网，您的邮箱验证码是" + code.toString();
        if (SendEmail.sendToMail(email.getEmail(), content)) {
            email.setCode(code);
            email.setSend_type(1);//1表示注册，更换邮箱使用的验证码，2表示找回密码使用的验证码
            if (this.moocService.findByEmail(email.getEmail()) > 0) {
                this.moocService.removeByEmail(email.getEmail());
            }
            Integer rows = this.moocService.insertEmailCode(email);
            if (rows > 0) {
                return request.getSession().getAttribute("user_session");
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 修改Email
     *
     * @param email
     * @param request
     * @return
     */
    @RequestMapping(value = "/users/update/email")
    @ResponseBody
    public User updateEmail(@RequestBody Email email, HttpServletRequest request) {
        String code = email.getCode();
        String emailaddr = email.getEmail();
        String sendCode = this.moocService.findCode(emailaddr);
        if (code.equals(sendCode)) {
            User user = new User();
            User user1 = (User) request.getSession().getAttribute("user_session");
            user.setEmail(emailaddr);
            user.setId(user1.getId());
            Integer rows = this.moocService.updateEmail(user);
            if (rows > 0) {
                return user1;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/users/update/pwd")
    @ResponseBody
    public User updatePwd(@RequestBody User user, HttpServletResponse response,
                          HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user1 = (User) session.getAttribute("user_session");
        user.setId(user1.getId());
        Integer rows = this.moocService.updatePwd(user);
        if (rows > 0) {
            session.invalidate();
            return user1;
        } else {
            return null;
        }
    }

    /*
    检查邮箱是否已被注册
     */
    @RequestMapping(value = "/checkEmail")
    public void checkEmail(@RequestBody Email email, HttpServletResponse response) throws Exception {
        JSONObject jsonObject = new JSONObject();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter printWriter = response.getWriter();
        if (this.moocService.findUserByEmail(email.getEmail()) != null) {
            jsonObject.put("result", "邮箱已被注册，请更换邮箱！或<a href='/login'>登录</a>");
        } else {
            jsonObject.put("result", "可以使用该邮箱注册");
        }
        printWriter.print(jsonObject.toString());
    }

    /*
    执行注册功能
     */
    @RequestMapping(value = "/register")
    public String register(Model model, String email, HttpSession session,
                           String password, String type) {
        if (type == null) {
            return "register";
        }
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        if (this.moocService.findUserByEmail(email) == null) {
            if (this.moocService.addUser(user) > 0) {
                User user1 = this.moocService.findUserByEmail(email);
                session.setAttribute("user_session", user1);
                return "redirect:/index";
            }
        }
        return "404";
    }

    @RequestMapping(value = "/message")
    public String message(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user_session");
        Integer id = user.getId();
        UserMessage userMessage = null;
        List<UserMessage> notRead = new ArrayList<UserMessage>();
        List<UserMessage> messages = this.moocService.findMessageByUser(id);
        if (messages != null) {
            Iterator iterator = messages.iterator();
            while (iterator.hasNext()) {
                userMessage = (UserMessage) iterator.next();
                if (userMessage.getHas_read() == 1) {
                    notRead.add(userMessage);
                }
            }
        }
        model.addAttribute("msgs", messages);
        model.addAttribute("notread", notRead);
        Integer rows = this.moocService.setMessageRead(user.getId());
        return "usercenter-message";
    }

    @RequestMapping(value = "/getnotread")
    public void getNotRead(HttpServletResponse response, HttpSession session) throws Exception {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        JSONObject jsonObject = new JSONObject();
        PrintWriter printWriter = response.getWriter();
        List<UserMessage> notRead = new ArrayList<UserMessage>();
        User user = (User) session.getAttribute("user_session");
        List<UserMessage> messages = this.moocService.findMessageByUser(user.getId());
        UserMessage userMessages = null;
        if (messages != null) {
            Iterator iterators = messages.iterator();
            while (iterators.hasNext()) {
                userMessages = (UserMessage) iterators.next();
                if (userMessages.getHas_read() == 1) {
                    notRead.add(userMessages);
                }
            }
            Integer count = notRead.size();
            jsonObject.put("count", count);
            printWriter.print(jsonObject.toString());
        }

    }

    /**
     * 显示用户中心用户学习过的课程
     *
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/user_mycourse")
    public String user_mycourse(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user_session");
        List<UserCourse> courses = this.moocService.findUserCourseInUserCenter(user);
        model.addAttribute("usercourse", courses);
        return "usercenter-mycourse";
    }

    /**
     * 显示用户中心用户收藏的内容
     */
    @RequestMapping(value = "/user_myfav")
    public String userMyFav(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user_session");
        Map map = new HashMap();
        map.put("type", 1);
        map.put("user_id", user.getId());
        Integer[] fav_ids = this.moocService.findUserFavs(map);
        List<Organization> organizationList = new ArrayList<Organization>();
        Organization organization = null;
        if (fav_ids.length > 0) {
            for (int i = 0; i < fav_ids.length; i++) {
                organization = this.moocService.findOrgById(fav_ids[i]);
                organizationList.add(organization);
            }
            model.addAttribute("orglist", organizationList);
        }
        return "usercenter-fav-org";
    }

    @RequestMapping(value = "/user_myfav_teacher")
    public String userMyFavTeacher(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user_session");
        Map map = new HashMap();
        map.put("type", 2);
        map.put("user_id", user.getId());
        Integer[] fav_ids = this.moocService.findUserFavs(map);
        List<Teacher> teacherList = new ArrayList<Teacher>();
        Teacher teacher = null;
        if (fav_ids.length > 0) {
            for (int i = 0; i < fav_ids.length; i++) {
                teacher = this.moocService.findTeacherById(fav_ids[i]);
                teacherList.add(teacher);
            }
            model.addAttribute("teachers", teacherList);
        }
        return "usercenter-fav-teacher";
    }

    @RequestMapping(value = "/user_myfav_course")
    public String userMyFavCourse(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user_session");
        Map<String, Integer> map = new HashMap();
        map.put("type", 3);
        map.put("user_id", user.getId());
        Integer[] fav_ids = this.moocService.findUserFavs(map);
        List<Course> courseList = new ArrayList<>();
        Course course = null;
        if (fav_ids.length > 0) {
            for (int i = 0; i < fav_ids.length; i++) {
                course = this.moocService.findCourseByIdDetail(fav_ids[i]);
                courseList.add(course);
            }
            model.addAttribute("courses", courseList);
        }
        return "usercenter-fav-course";
    }

    @RequestMapping(value = "/deleteFav")
    public void deleteFav(@RequestBody RemoveTemp removeTemp, HttpServletResponse response,
                          HttpSession session) throws Exception {
        User user = (User) session.getAttribute("user_session");
        switch (removeTemp.getType()) {
            case 1:
                this.moocService.removeFav_nums_org(removeTemp.getId());
                break;
            case 2:
                this.moocService.updateFavnumsreduce(removeTemp.getId());
                break;
            case 3:
                this.moocService.removeFav_nums(removeTemp.getId());
                break;
        }
        Map map = new HashMap();
        map.put("id", removeTemp.getId());
        map.put("type", removeTemp.getType());
        map.put("user_id", user.getId());
        Integer rows = this.moocService.deleteUserFav(map);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter printWriter = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        if (rows > 0) {
            jsonObject.put("msg", "删除成功");
        } else {
            jsonObject.put("msg", "删除失败");
        }
        printWriter.print(jsonObject.toString());
    }

    @RequestMapping(value = "/reset_password")
    public String reset_password() {
        return "forgetpwd";
    }

    @RequestMapping(value = "/doreset_pwd")
    public String doresetpwd(@RequestBody Email emails, HttpServletResponse response, String type,String code) throws Exception {
        if (type.equals("reset")) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter printWriter = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            String someCode = MakeCode.code(32);
            String content = "尊敬的的用户" + emails.getEmail() + "您正在使用重置密码服务，请点击下列链接完成重置验证" + "http://localhost:8080/showReset?code=" +
                    someCode+"&account="+emails.getEmail();
            if (this.moocService.findUserByEmail(emails.getEmail())!=null) {
                if (SendEmail.sendToMail(emails.getEmail(), content)) {
                    jsonObject.put("msg", "验证邮件发送成功，请登录邮箱查看，完成验证");
                }
            } else {
                jsonObject.put("msg", "验证失败，请检查邮箱是否合法或是否使用该邮箱注册");
            }
            printWriter.print(jsonObject.toString());
            return null;
        }
        return null;
    }
    @RequestMapping(value = "/showReset")
    public String showReset(String code){
        return "password_reset";
    }

    @RequestMapping(value = "/changePassword")
    public String changePassword(String account,String password){
      TempEmail tempEmail = new TempEmail();
      tempEmail.setEmail(account);
      tempEmail.setPassword(password);
      if (this.moocService.changeUserPassword(tempEmail)>0){
          return "login";
      }
      return "register";
    }
}

